package com.xb.cloud.order.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xb.cloud.order.service.client.PaymentFlowService;
import com.xb.cloud.order.service.client.PaymentService;
import com.xb.cloud.order.service.client.SellOrderService;
import com.xb.cloud.order.service.client.bo.PaymentFlowBo;
import com.xb.cloud.order.service.client.bo.SellOrderBo;
import com.xb.cloud.product.merchant.service.client.ShopService;
import com.xb.cloud.product.merchant.service.client.bo.ShopBo;
import com.xb.cloud.service.client.ServiceReturnCodes;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;
import com.xb.cloud.shopping.service.client.vo.PaymentRequestVo;
import com.xb.cloud.shopping.service.client.vo.PaymentShopInfo;

/**
 * 支付相关的操作
 * 
 * @ClassName: PaymentServiceImpl
 * @Description:TODO
 * @author: 鲜备科技
 * @date: 2018年1月24日 上午9:48:28
 * 
 * @Copyright: 2018 www.xianbeitech.com Inc. All rights reserved.
 *
 */
@Service
public class PaymentServiceImpl implements PaymentService {
	@Resource
	ShopService shopService;

	@Resource
	SellOrderService sellOrderService;

	@Resource
	PaymentFlowService paymentFlowService;

	@Override
	public ServiceReturnInfo getShopPaymentInfo(PaymentRequestVo requestVo) {

		ServiceReturnInfo returnInfo = shopService.getShopBoById(requestVo.getShopId());
		ShopBo shopBo = (ShopBo) returnInfo.getData();
		if (null != shopBo) {
			PaymentShopInfo shopInfo = new PaymentShopInfo();
			shopInfo.setShopId(shopBo.getId());
			shopInfo.setShopName(shopBo.getShopNameCn());
			shopInfo.setReceiptCodeUrl(shopBo.getReceiptCodeUrl());
			shopInfo.setOpenId(shopBo.getOpenId());
			shopInfo.setOpenKey(shopBo.getOpenKey());
			return ServiceReturnUtils.success(shopInfo);
		}
		return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_DETAIL_NOT_EXIST_EXCEPTION);
	}

	@Override
	@Transactional(value = "transactionManager_order")
	public ServiceReturnInfo completePayment(PaymentFlowBo paymentFlowBo) {
		Long soId = paymentFlowBo.getSoId();
		Integer paymentStatus = paymentFlowBo.getPaymentStatus();

		if (paymentStatus == 1) {
			// 支付成功，修改订单状态和支付信息
			SellOrderBo sellOrderBo = new SellOrderBo();
			sellOrderBo.setId(soId);
			ServiceReturnInfo returnInfo = sellOrderService.completeOrderPayment(sellOrderBo);
			String code = returnInfo.getCode();

			// 当订单不存在或者订单状态错误时，应该返回给支付回调方成功信息。防止支付回调方重复调用通知接口
			if (ServiceReturnUtils.isError(returnInfo)
					&& !(ServiceReturnCodes.ORDER_STATUS_INVALID.getCode().equals(code)
							|| ServiceReturnCodes.ORDER_NOT_EXIST.getCode().equals(code))) {
				return returnInfo;// 返回订单更新错误
			}
		}

		// 订单更新成功后再更新支付流水状态
		ServiceReturnInfo returnInfo = paymentFlowService.updateStatus(paymentFlowBo);
		if (ServiceReturnUtils.isError(returnInfo)) {
			return returnInfo;
		}

		return ServiceReturnUtils.success();
	}

}
